package cl.gob.minvu.catastromobile;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import cl.gob.minvu.catastromobile.dao.FichaDAO;
import cl.gob.minvu.catastromobile.to.FichaTO;
import cl.gob.minvu.catastromobile.util.GenericUtil;
import cl.gob.minvu.catastromobile.util.Logger;
import cl.gob.minvu.catastromobile.util.RestService;

import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

/**
 * @author psep
 * 
 */
public class SyncActivity extends AbstractActivity {

	private static final Logger logger = Logger.getLogger(SyncActivity.class);

	private ListView pendientesListView;
	private List<FichaTO> fichas;
	private Button btnSync;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sync);

		this.pendientesListView = (ListView) super
				.findViewById(R.id.pendiente_list);
		this.btnSync = (Button) super.findViewById(R.id.btnSync);
		this.loadList();
	}

	/**
	 * 
	 */
	private void loadList() {
		this.fichas = new FichaDAO(this).getAllBySync();
		int cursor = this.fichas.size();

		if (cursor > 0) {
			String[] lista = new String[cursor];

			for (int i = 0; i < cursor; i++) {
				FichaTO fichaTO = this.fichas.get(i);
				lista[i] = "Ficha " + fichaTO.getId() + "\n"
						+ fichaTO.getNombreJefeHogar();
			}

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, lista);
			this.pendientesListView.setAdapter(adapter);
		}
	}

	/**
	 * @author psep
	 * 
	 */
	private class HttpFichaTask extends AsyncTask<String, Void, String> {

		private String idFicha;
		
		@Override
		protected String doInBackground(String... args) {
			this.idFicha = args[1];
			return RestService.POST(args[0], this.getEntity(args[2], args[3]));
		}

		@Override
		protected void onPostExecute(String result) {
			updateFicha(Integer.parseInt(this.idFicha), result);
		}

		/**
		 * @param ficha
		 * @param foto
		 * @return
		 */
		private UrlEncodedFormEntity getEntity(String ficha, String foto) {
			UrlEncodedFormEntity url = null;

			try {
				BasicNameValuePair json = new BasicNameValuePair("object",
						GenericUtil.encode(ficha));
				BasicNameValuePair json2 = new BasicNameValuePair("foto", foto);
				List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
				nameValuePairList.add(json);
				nameValuePairList.add(json2);

				url = new UrlEncodedFormEntity(nameValuePairList);
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage());
			}

			return url;
		}
	}
	
	/**
	 * @param id
	 * @param result
	 */
	public void updateFicha(int id, String result) {
		try {
			JSONObject json = new JSONObject(result);
			int codigo = json.getInt("e");
			
			if (codigo == 0) {
				this.getNotification("Sincronización exitosa", "La ficha ha sido ingresada al Sistema");
				new FichaDAO(this).updateSync(id);
			} else {
				this.getNotification("Problemas al sincronizar", RestService.getErrorMessage(result));
			}
			
		} catch (JSONException e) {
			logger.error(e.getMessage());
		}
		
		this.pendientesListView.setAdapter(null);
		this.loadList();
	}
	
	/**
	 * @param title
	 * @param msg
	 */
	public void getNotification(String title, String msg) {
		Intent resultIntent = new Intent(this, SyncActivity.class);
		
		PendingIntent resultPendingIntent =
			    PendingIntent.getActivity(
			    this,
			    0,
			    resultIntent,
			    PendingIntent.FLAG_UPDATE_CURRENT
			);
		
		Builder mBuilder =
			    new Builder(this)
			    .setSmallIcon(R.drawable.logo_minvu)
			    .setContentTitle(title)
			    .setContentText(msg)
			    .setContentIntent(resultPendingIntent);
		
		int mNotificationId = 001;
		NotificationManager mNotifyMgr = 
		        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mNotifyMgr.notify(mNotificationId, mBuilder.build());
	}

	/**
	 * @param button
	 */
	public void onClickSend(View button) {
		if (this.fichas != null && this.fichas.size() > 0) {
			super.toastMsg("Sincronizando...");
			this.btnSync.setEnabled(false);

			// TODO verificar url
			String url = "http://10.150.203.71:8080/Catastro/CreaFicha";

			for (FichaTO fichaTO : this.fichas) {
				new HttpFichaTask().execute(url, Integer.toString(fichaTO.getId()),
						fichaTO.getFicha(), fichaTO.getPhoto1());
			}
			
			this.btnSync.setEnabled(true);
		}
	}

	@Override
	public void reset() {
	}

	@Override
	public boolean validateFrm() {
		return false;
	}
}
